﻿namespace LiteBlog.Components
{
    using System.Collections.Generic;
    using System.Linq;
    using LiteBlog.Common.Components;
    using LiteBlog.Common.Entities;
    using LiteBlog.Components.Contracts;
    using LiteBlog.Components.Enums;
    using LiteBlog.Repositories.Contracts;

    public class CommentComp : BaseComp<ICommentRepository>, ICommentComp
    {
        public CommentComp(ICommentRepository data, ICacheComp cache, SettingsComp settingsComp) : base(data, cache)
        {
            _settingsComp = settingsComp;
        }

        private SettingsComp _settingsComp;
        public SettingsComp SettingsComponent
        {
            get
            {
                return _settingsComp;
            }
        }

        public IEnumerable<Comment> Get()
        {
            var comments = _cache.Get<IEnumerable<Comment>>(CacheType.Comments);
            if (comments == null)
            {
                comments = _data.Get();
                _cache.Put(CacheType.Comments, comments);
            }
            return comments;
        }

        public List<Comment> GetUnapproved()
        {
            return Get().Where(c => !c.IsApproved).ToList();
        }

        public List<Comment> GetApproved()
        {
            return Get().Where(c => c.IsApproved).ToList();
        }

        public Comment Get(string id)
        {
            return Get().SingleOrDefault(c => c.ID == id);
        }

        public MethodResult Create(Comment comment)
        {
            bool commentModeration = SettingsComponent.Load().CommentModeration;
            comment.Text = comment.RawComment;
            comment.IsApproved = !commentModeration || comment.IsAuthor;
            _data.Create(comment);
            return comment.IsApproved ? MethodResult.CreateSuccess : MethodResult.Pending;
        }

        public MethodResult Update(string olid, Comment comment)
        {
            comment.Text = comment.RawComment; // will process
            _data.Update(olid, comment);
            return MethodResult.UpdateSuccess;
        }

        public MethodResult Delete(string id)
        {
           _data.Delete(id);
           return MethodResult.DeleteSuccess;
        }

        public MethodResult Approve(string id)
        {
            _data.Approve(id);
            return MethodResult.ApproveSuccess;
        }

        public MethodResult Reject(string id)
        {
            _data.Reject(id);
            return MethodResult.RejectSuccess;
        }
    }
}